import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/pages/mine/apartment_manage/water_electricity_setting/api.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class AuthorizationManagement extends StatefulWidget {
  const AuthorizationManagement({Key? key}) : super(key: key);

  @override
  State<AuthorizationManagement> createState() => _AuthorizationManagementState();
}

class _AuthorizationManagementState extends State<AuthorizationManagement> {
  final TextEditingController _authController = TextEditingController();
  final TextEditingController _noStrController = TextEditingController();
  String? _waterElectricityConfigId;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadConfigInfo();
  }

  @override
  void dispose() {
    _authController.dispose();
    _noStrController.dispose();
    super.dispose();
  }

  // 加载配置信息
  Future<void> _loadConfigInfo() async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      final result = await waterElectricitySettingApi.getConfigInfo();
      
      if (result['code'] == 200 && result['data'] != null) {
        final data = result['data'];
        setState(() {
          _waterElectricityConfigId = data['waterElectricityConfigId']?.toString();
          _authController.text = data['auth']?.toString() ?? '';
          _noStrController.text = data['noStr']?.toString() ?? '';
        });
      }
    } catch (e) {
      print('加载配置信息失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 保存配置
  Future<void> _saveConfig() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final data = {
        'waterElectricityConfigId': _waterElectricityConfigId,
        'auth': _authController.text,
        'noStr': _noStrController.text,
      };

      final result = await waterElectricitySettingApi.editConfig(data);
      
      if (result['code'] == 200) {
        EasyLoading.showSuccess("保存成功");
      } else {
        EasyLoading.showError("保存失败: ${result['message'] ?? '未知错误'}");
      }
    } catch (e) {
      EasyLoading.showError("保存失败: $e");
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "授权管理",
      child: _isLoading && _waterElectricityConfigId == null
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: EdgeInsets.all(ThemeVars.paddingPage),
              child: Column(
                children: [
                  MenuBlock(
                    items: [
                      MenuBlockItem(
                        text: "授权码",
                        showArrow: false,
                        suffix: TextField(
                          controller: _authController,
                          textAlign: TextAlign.right,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            hintText: "请输入授权码",
                            hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                            isDense: true,
                          ),
                        ),
                      ),
                      MenuBlockItem(
                        text: "随机字符串",
                        showArrow: false,
                        suffix: TextField(
                          controller: _noStrController,
                          textAlign: TextAlign.right,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            hintText: "请输入随机字符串",
                            hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                            isDense: true,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  SizedBox(
                    width: double.infinity,
                    child: Button(
                      onPressed: _isLoading ? null : _saveConfig,
                      child: _isLoading ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      ) : const Text("保存"),
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}